package com.start.system.user.controller;

import com.start.common.api.Result;
import com.start.common.details.BaseUserDetail;
import com.start.common.entity.StartBaseMenu;
import com.start.core.annotations.StartLog;
import com.start.core.enums.MenuPositionEnum;
import com.start.core.enums.MenuType;
import com.start.security.StartTokenTools;
import com.start.security.StartUserPermissionTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user/menu")
public class UserMenuController {

    private static final Predicate<StartBaseMenu<?>> MENU_FILTER = startBaseMenu -> {
        if (!MenuType.MENU.isMatch(startBaseMenu.getMenuType())) {
            return false;
        }
        return startBaseMenu.getEnable() != 0;
    };

    @Autowired
    private StartUserPermissionTools userPermissionTools;

    @GetMapping("/getMenu")
    @StartLog(value = "当前用户", action = "获取菜单")
    public Result<?> getMenu() {
        BaseUserDetail currentUser = StartTokenTools.getCurrentUser();
        List<StartBaseMenu<?>> menus = userPermissionTools.getUserMenu(currentUser);
        Predicate<StartBaseMenu<?>> filter = MENU_FILTER.and(startBaseMenu -> MenuPositionEnum.LEFT.isMatch(startBaseMenu.getMenuPosition()));
        menus = menus.stream()
                .filter(filter)
                .sorted(Comparator.comparingInt(StartBaseMenu::getMenuSort))
                .collect(Collectors.toList());
        return Result.ok(menus);
    }

    @GetMapping("/getTopMenu")
    public Result<?> getTopMenu() {
        BaseUserDetail currentUser = StartTokenTools.getCurrentUser();
        List<StartBaseMenu<?>> menus = userPermissionTools.getUserMenu(currentUser);
        Predicate<StartBaseMenu<?>> filter = MENU_FILTER.and(startBaseMenu -> MenuPositionEnum.TOP.isMatch(startBaseMenu.getMenuPosition()));

        menus = menus.stream().filter(filter).sorted(Comparator.comparingInt(StartBaseMenu::getMenuSort)).collect(Collectors.toList());
        return Result.ok(menus);
    }

    @GetMapping("/getUserPermissions")
    @StartLog(value = "当前用户", action = "获取已拥有的权限")
    public Result<?> getUserPermissions() {
        BaseUserDetail currentUser = StartTokenTools.getCurrentUser();
        List<StartBaseMenu<?>> menus = userPermissionTools.getUserMenu(currentUser);
        List<StartBaseMenu<?>> collect = menus.stream().filter(e -> !StringUtils.isEmpty(e.getMenuCode())).collect(Collectors.toList());
        return Result.ok(collect);
    }
}
